package com.wnhz.work.yz.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.alipay.PayResult;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.ALiBean;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.GoToOrderBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GotoOrderActivity extends BaseActivity implements View.OnClickListener {
    private GoToOrderBean.InfoEntity info1 = new GoToOrderBean.InfoEntity();
    private TextView order_num, time, money, need_pay, need_pay2, wallet;
    private RecyclerView recycler;
    private LinearLayout ll_ali, ll_yue;
    private ImageView ali_img, yue_img;
    private int pay = 1;

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("支付");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        ImageView ic_telephone = (ImageView) findViewById(R.id.ic_telephone);
        ic_telephone.setOnClickListener(this);
        ic_telephone.setVisibility(View.GONE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goto_order);
        ll_ali = (LinearLayout) findViewById(R.id.ll_ali);
        ll_yue = (LinearLayout) findViewById(R.id.ll_yue);
        ll_ali.setOnClickListener(this);
        ll_yue.setOnClickListener(this);
        ali_img = (ImageView) findViewById(R.id.ali_img);
        yue_img = (ImageView) findViewById(R.id.yue_img);
        findViewById(R.id.btn).setOnClickListener(this);
        initTitle();

        info1 = (GoToOrderBean.InfoEntity) getIntent().getSerializableExtra("info1");
        order_num = (TextView) findViewById(R.id.order_num);
        order_num.setText("订单号：" + info1.getOrder_no());
        money = (TextView) findViewById(R.id.money);
        money.setText(info1.getAmount() + "元");
        need_pay = (TextView) findViewById(R.id.need_pay);
        need_pay.setText("￥" + info1.getNeedPay() + "元");
        need_pay2 = (TextView) findViewById(R.id.need_pay2);
        need_pay2.setText("￥" + info1.getNeedPay() + "元");
        wallet = (TextView) findViewById(R.id.wallet);
        try {
            Double.parseDouble(info1.getWallet());
            wallet.setText("(账户余额" + info1.getWallet() + "元)");
        } catch (Exception e) {
            wallet.setText("(账户余额" + info1.getWallet() + ")");
        }


        time = (TextView) findViewById(R.id.time);
        time.setText("提交日期：" + info1.getCreate_time());
        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recycler.setAdapter(new BaseRVAdapter(this, info1.getList()) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_order;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                x.image().bind(holder.getImageView(R.id.img), info1.getList().get(position).getGoods_img());
                holder.setTextView(R.id.title, info1.getList().get(position).getGoods_name());
                holder.setTextView(R.id.type, info1.getList().get(position).getGoods_name());
                holder.setTextView(R.id.area, info1.getList().get(position).getGoods_des());
                holder.setTextView(R.id.num, "x" + info1.getList().get(position).getNums());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.ll_ali:
                ali_img.setImageResource(R.mipmap.ic_choose_li);
                yue_img.setImageResource(R.mipmap.ic_choose_nor);
                pay = 1;
                break;
            case R.id.ll_yue:
                yue_img.setImageResource(R.mipmap.ic_choose_li);
                ali_img.setImageResource(R.mipmap.ic_choose_nor);
                pay = 2;
                break;
            case R.id.btn:

                upPay();

                break;
        }
    }

    private static final int TOALIPAY = 3;
    private static final int SDK_PAY_FLAG = 1;

    private void upPay() {
        String url = "";
        if (pay == 1) {
            //  MyToast("支付宝");
            url = Url.DECORATE_ALIPAY;
        } else {
            // MyToast("余额");
            url = Url.DECORATE_WALLETPAY;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("order_no", info1.getOrder_no());
        showDialog();
        XUtil.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        if (pay == 1) {
                            Gson gson = new Gson();
                            ALiBean bean = gson.fromJson(result, ALiBean.class);
                            if ("1".equals(bean.getResult())) {
                                Message msg2 = Message.obtain();
                                msg2.what = TOALIPAY;
                                msg2.obj = bean.getInfo();
                                mHandler.sendMessage(msg2);
                            }
                        } else {
                            setStart(info1.getOrder_no(), info1.getNeedPay());
                        }
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });


    }

    private void setStart(String str_number, String price) {
        Intent intent = new Intent(this, PaySuccessActivity.class);
        //   Log.e("----",infos.optString("order_no"));
        intent.putExtra("str_number", str_number);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        intent.putExtra("str_tiem", df.format(new Date()));
        intent.putExtra("str_price", price);
        startActivity(intent);
/**
 * install0
 installyu
 install1
 look2
 detail_topay
 install2
 yuyue3
 details3
 */
//        MyApplication.getInstance().destoryActivity("install0");
//        MyApplication.getInstance().destoryActivity("installyu");
//        MyApplication.getInstance().destoryActivity("install1");
//        MyApplication.getInstance().destoryActivity("look2");
//        MyApplication.getInstance().destoryActivity("detail_topay");
//        MyApplication.getInstance().destoryActivity("install2");
//        MyApplication.getInstance().destoryActivity("yuyue3");
//        MyApplication.getInstance().destoryActivity("details3");
        EventBus.getDefault().post(new Finish1());
        finish();

    }

    public void payV2(ALiBean.InfoEntity info) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        final String orderinfo = "_input_charset=\"" + info.get_input_charset() + "\"&body=\"" + info.getBody() + "\"&notify_url=\"" + info.getNotify_url() + "\"&out_trade_no=\"" + info.getOut_trade_no() + "\"&partner=\"" + info.getPartner() + "\"&payment_type=\"" + info.getPayment_type() + "\"&seller_id=\"" + info.getSeller_id() + "\"&service=\"" + info.getService() + "\"&subject=\"" + info.getSubject() + "\"&total_fee=\"" + info.getTotal_fee() + "\"&sign=\"" + info.getSign() + "\"&sign_type=\"" + info.getSign_type() + "\"";

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(GotoOrderActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.e("=======支付宝结果  msp====", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //   Log.e("-----", resultInfo + "---" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(GotoOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        //  setStart(budget_no, pay_money, pay_type);
                        setStart(info1.getOrder_no(), info1.getNeedPay());

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(GotoOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                case TOALIPAY: {
                    ALiBean.InfoEntity obj = (ALiBean.InfoEntity) msg.obj;
                    payV2(obj);
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


}
